package com.ctg.payroll2.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ctg.payroll2.bean.po.workflow.FlowOrgchart;


public class FlowOrgchartMenuRecursion {
	private StringBuffer returnStr = new StringBuffer();

	private void recursionFn(List<FlowOrgchart> list, FlowOrgchart node) {
		
		if (hasChild(list, node)) {
			returnStr.append("{id:'");
			returnStr.append(node.getFlow_orgid()).append("'");
			returnStr.append(",text:'");
			returnStr.append(node.getFlow_orgname()).append("'");
			
			returnStr.append(",children:[");
			List childList = getChildList(list, node);
			Iterator it = childList.iterator();
			while (it.hasNext()) {
				FlowOrgchart n = (FlowOrgchart) it.next();
				recursionFn(list, n);
			}
			returnStr.append("]},");
		} else {
			returnStr.append("{id:'");
			returnStr.append(node.getFlow_orgid()).append("'");
			returnStr.append(",text:'");
			returnStr.append(node.getFlow_orgname()).append("'");
			returnStr.append(",action:'");
			returnStr.append(node.getFlow_url()).append("'");
			returnStr.append(",leaf:true},");
			
		}
		
	}

	private boolean hasChild(List<FlowOrgchart> list, FlowOrgchart node) { // 判断是否有子节点
		return getChildList(list, node).size() > 0 ? true : false;
	}

	private List<FlowOrgchart> getChildList(List<FlowOrgchart> list,
			FlowOrgchart node) { // 得到子节点列表
		List<FlowOrgchart> li = new ArrayList<FlowOrgchart>();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			FlowOrgchart n = (FlowOrgchart) it.next();
			if ((n.getFlow_orgsupid().toString()).equals((node.getFlow_orgid().toString()))) {
				li.add(n);
			}
		}
		return li;
	}

	private String modifyStr(String returnStr) {// 修饰一下才能满足Extjs的Json格式
		return ("[" + returnStr + "]").replaceAll(",]", "]");

	}

	public static String getString(List<FlowOrgchart> nodeList) {
		FlowOrgchartMenuRecursion r = new FlowOrgchartMenuRecursion();
		
		r.recursionFn(nodeList, nodeList.get(0));

		return r.modifyStr(r.getReturnStr());
	}

	public String getReturnStr() {
		return returnStr.toString();
	}

}